package org.jeecg.lawcase.data.reader.impl;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import io.micrometer.core.instrument.util.IOUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.lawcase.data.reader.DataImportApadter;
import org.jeecg.lawcase.data.reader.DataImportManager;
import org.jeecg.lawcase.data.reader.DataTemplate;
import org.springframework.stereotype.Component;

import java.io.InputStream;

@Component
public class PDFDataImportImpl implements DataImportApadter {

    public PDFDataImportImpl() {
        DataImportManager.registerService(this.getFileType(), this);
    }

    @Override
    public String getFileType() {
        return "pdf";
    }

    @Override
    public DataTemplate importData(String fileName, InputStream inputStream) {
        DataTemplate dataTemplate = new DataTemplate();
        String content = this.readContent(inputStream);
        this.parseContent(dataTemplate, content);
        return dataTemplate;
    }

    /**
     * 解析数据
     * @param dataTemplate
     * @param content
     */
    private void parseContent(DataTemplate dataTemplate, String content){

    }

    /**
     * 读取pdf内容数据
     * @param inputStream
     * @return
     */
    private String readContent(InputStream inputStream) {
        String readerContent = null;
        int numberOfPages = 0;
        try{
            PdfReader pdfReader = new PdfReader(inputStream);
            PdfDocument pdfDocument = new PdfDocument(pdfReader);
            numberOfPages = pdfDocument.getNumberOfPages();
            readerContent = IOUtils.toString(inputStream);
        } catch (Exception e){
            throw new JeecgBootException("PDF识别报错", e);
        }

        // 检测PDF是否识别出内容标志（纯图片格式每页为2个\n符号 - 2个字节长度）
        if (readerContent != null && readerContent.length() > (numberOfPages * 2)) {
            // 普通PDF，使用默认识别的内容
            return readerContent;
        } else {
            throw new JeecgBootException("PDF无法识别");
        }
    }
}
